var Player = require("./player")
var FightAttri = require("./fightAttri")
var prefixAttri = require("./prefixAttri")
var redisClient = require('../dao/redis/redisClient')
var
    NORMALATTACK = 1
PHYSICALATTACK = 2
SKILLATTACK = 3
exports.startBattle = function(player1, player2) {
    var buffsOper = []
    fightRecords = {
        roundCount: 0,
        team1: [],
        team2: [],
        fightActions: [],
        buffs: []
    }

    var j = {
        name: player1.name,
        maxHp: player1.maxHp,
        hp: player1.hp,
        pos: 1
    }
    fightRecords.team1.push(j)
    var fightAttri1 = new FightAttri(player1.fightAttri)
    fightAttri1.pos = 1


    var fightAttri2 = new FightAttri(player2.fightAttri)
    var pre = 0;
    if (player2.prefixAttri.length > 0) {
        if (Math.floor(Math.random() * 100) > 50) {
            var index = Math.floor(Math.random() * player2.prefixAttri.length)
            var pre = player2.prefixAttri[index]
            console.log('pre:' + pre);
            prefixAttri[pre](fightAttri2, player2.lvl)
        }
    }

    var j = {
        name: player2.name,
        maxHp: player2.maxHp,
        pre: pre,
        hp: player2.hp,
        pos: 2
    }
    fightRecords.team2.push(j)
    fightAttri2.pos = 2

    var round = 0
    while (true) {
        battling(fightAttri1, fightAttri2, fightRecords, buffsOper, round)
        if (fightAttri2.hp <= 0) {
            break
        }

        battling(fightAttri2, fightAttri1, fightRecords, buffsOper, round)
        if (fightAttri1.hp <= 0) {
            break
        }
        //回合结束 计算buff
        var length = buffsOper.length
        var buffs = []
            /*
                    for (var i = length - 1; i >= 0; i--) {
                        gBuffOper[i].tick--
                        if (gBuffOper[i].tick === 0) {
                            buffOper(gBuffOper[i].id, gBuffOper[i].player, gBuffOper[i].value)
                            gBuffOper.splice(i, 1)
                        } else {
                            var buff = {
                                id: gBuffOper[i].id,
                                tick: gBuffOper[i].tick,
                                pos: gBuffOper[i].player.pos,
                                round: round
                            }
                            buffs.push(buff)
                        }
                    }
                    fightRecords.buffs.push(buffs)*/
        round++
    }
    fightRecords.roundCount = round //战斗总回合数

    if (fightAttri2.hp <= 0) {
        //战斗胜利计算奖励
        calcReward(player1, player2, fightRecords)
    }
    player1.recordFight(fightRecords)
    return fightRecords
}

function battling(attacker, defender, fightRecords, buffsOper, round) {
    var defenderRecords = []
    var skillId
    if (attacker.battleStatus === 1) {
        skillId = -attacker.battleStatus
    } else {
        skillId = SkillAttack(attacker, defender, buffsOper, defenderRecords)
    }
    var attackerRecord = {
        hp: attacker.hp,
        skillId: skillId,
        pos: attacker.pos
    }
    var fightAction = {
        round: round,
        attackerRecord: attackerRecord,
        defenderRecords: defenderRecords
    }
    fightRecords.fightActions.push(fightAction)
}

function SkillAttack(attacker, defender, buffsOper, defenderRecords) {
    var opt = {
        damagePer: 0,
        avoidRate: 0,
        critRate: 0,
        critHurt: 0,
        vampirePer: 0,
        damage: 0,
        hitRate: 0,
        attack: 0,
        reduceDefendPer: 0,
        reduceDamagePer: 0
    }
    var skillId = attacker.skills[attacker.skillPos]
        //  console.log(attacker.name + '使用了技能' + skillId)
    switch (skillId) {
        case 0:
            //普通攻击：
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        case 101000:
            //血性狂击。攻击敌人，并恢复伤害的20%的血量(物理)
            opt.vampirePer = 20
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        case 107000:
            //弈剑回风：暴击率提升10%对单个敌人施展物理攻击(物理)
            opt.critRate = 10
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        case 201000:
            //烽火连天 连续攻击单个敌人2次。(物理)
            battle(attacker, defender, defenderRecords, SKILLATTACK, opt, null, 2)
            break
        case 202000:
            //鬼舞斩杀：100%暴击(物理)
            opt.critRate = 1000
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        case 204000:
            //腐蚀之箭：使武器带上腐蚀的buff。buff持续3回合(物理)
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt, function(p, popt) {
                p.defend = p.defend - 10
                var buff = {
                    id: 203000,
                    tick: 3,
                    value: [-10],
                    player: p
                }
                buffOper.push(buff)
            })
            break
        case 205000:
            //破血狂攻：无视敌人10%护甲，伤害增加30%，暴击率提升30%(物理)
            opt.damageRate = 30
            opt.critRate = 30
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt, function(p, popt) {
                popt.reduceDefend = p.defend * 0.1
            })
            break
        case 206000:
            //炼魂：提升命中率，暴击率，暴击伤害，buff
            attacker.hitRate = attacker.hitRate + 10
            attacker.critRate = attacker.critRate + 10
            attacker.critHurt = attacker.critHurt + 10
            var buff = {
                id: 206000,
                tick: 3,
                value: [10, 10, 10],
                player: attacker
            }
            buffOper.push(buff)
            break
        case 207000:
            //凝风斩：对单个敌人施展攻击(技能)
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        case 301000:
            //点穴封脉: 使单个敌人在一定回合内无法恢复生命。
            var index = Math.floor(Math.random() * defendQueue.length)
            defendQueue[index].status = 1
            var buff = {
                id: 301000,
                tick: 3,
                player: defendQueue[index]
            }
            buffOper.push(buff)
            break
        case 306000:
            //回风拂柳: 对单个敌人进行连续两次的物理攻击(物理)
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, {}, 2)
        case 307000:
            //去腐生肌: 回复单个队友的血量
            var index = Math.floor(Math.random() * adlen)
            var p = atmp[adqueue[index]]
            if (p.status !== 1) {
                p.hp = p.hp + 150
            }
            break
        case 308000:
            //炽热光环，为队友提供一个20%减伤护盾，护盾持续3回合
            var k = getRandom(adlen, 3)
            for (var i = 0; i < num; i++) {
                var p = atmp[adqueue[k[num]]]
                p.reduceDamagePer = p.reduceDamagePer + 20
                var buff = {
                    id: 308000,
                    tick: 3,
                    value: [20],
                    player: p
                }
                buffOper.push(buff)
            }
            break
        case 401000:
            //舍我其谁：附加失去血量的百分比伤害
            opt = {
                damageRate: (1 - attacker.hp / attacker.maxHp)
            }
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        case 403000:
            //孤注一掷：伤害增加30%
            opt.damageRate + 30
            battle(attacker, defender, defenderRecords, SKILLATTACK, opt)
            break
        case 404000:
            //暴怒：提升自身的攻击力和防御力
            attacker.attack = attacker.attack + 10
            attacker.defend = attacker.defend + 10
            var buff = {
                id: 404000,
                tick: 3,
                value: [10, 10],
                player: attacker
            }
            buffOper.push(buff)
        case 405000:
            //冲撞：附加额外伤害，并一定概率击晕敌人，使敌人无法行动一回合
            opt.damageRate = 30
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt, function(p) {
                p.battleStatus = 1 //眩晕，昏睡，
                var buff = {
                    id: 405000,
                    tick: 2,
                    player: p
                }
                buffOper.push(buff)
            })
            break
        case 407000:
            //嗜血狂袭
            opt.vampirePer = 20
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
        default:
            //普通攻击：
            battle(attacker, defender, defenderRecords, PHYSICALATTACK, opt)
            break
    }

    // attacker.skillPos = attacker.skillPos === attacker.skills.length ? 0 : attacker.skillPos + 1
    return skillId
}

function buffOper(id, player, value) {
    switch (id) {
        case 203000:
            //腐蚀之箭：使武器带上腐蚀的buff。buff持续3回合
            player.defend -= value[0]
            break
        case 206000:
            //炼魂：提升命中率，暴击率，暴击伤害，buff
            player.hitRate -= value[0]
            player.critRate -= value[1]
            player.critHurt -= value[2]
            break
        case 301000:
            //点穴封脉: 使单个敌人在一定回合内无法恢复生命。
            player.status = 0
            break
        case 308000:
            //炽热光环，为队友提供一个20%减伤护盾，护盾持续3回合
            player.reduceDamagePer -= value[0]
            break
        case 404000:
            //暴怒：提升自身的攻击力和防御力
            player.attack -= value[0]
            player.defend -= value[1]
            break
        case 405000:
            //冲撞：附加额外伤害，并一定概率击晕敌人，使敌人无法行动一回合
            player.battleStatus = 1
            break
    }
}

function battle(attacker, defender, defenderRecords, attackType, opt, func, times) {
    var oper = {
        reacOper: 0,
        vampireHurt: 0,
        damage: 0
    }
    times = times ? times : 1
    for (var i = 0; i < times; i++) {
        if (func) {
            func(defender, opt)
        }
        calcSkilldamage(attacker, defender, attackType, oper, opt)

        defenderRecord = {
            hp: defender.hp,
            oper: oper,
            pos: defender.pos,
            //player: new playerAttri.Player(p)
        }
        defenderRecords.push(defenderRecord)
    }
}

//计算技能伤害
function calcSkilldamage(attacker, defender, attackType, oper, opt) {

    if (opt.damage > 0) {
        //固定伤害
        defender.hp = damage = defender.hp - damage
        oper.damage = opt.damage
        console.log(defender.name + '受到' + attacker.name + '的' + opt.damage + '固定伤害—(' + attacker.name + '的hp:' + attacker.hp + '' + defender.name + '的hp:' + defender.hp + ')')
        return
    }
    var damage = 0
    var damagePer = 100
    var content = ''
    if (attackType !== 3) {
        //是否闪避
        var rate = defender.avoidRate - opt.hitRate - attacker.hitRate
        rate = rate > 80 ? 80 : rate
        if ((Math.random() * 100) <= rate) {
            oper.reacOper = 2
            console.log(defender.name + '闪避了' + attacker.name + '的攻击——————(' + attacker.name + '的hp:' + attacker.hp + '' + defender.name + '的hp:' + defender.hp + ')')
            return
        }
    }
    if (attackType !== 3) {
        //是否暴击
        rate = attacker.critRate + opt.critRate - defender.toughnessRate
        if ((Math.random() * 100) <= rate) {
            oper.reacOper = 1
            damagePer = damagePer + attacker.critHurt + opt.critHurt
        }
    }
    //计算伤害
    var extraAttack = Math.floor(Math.random() * Math.floor((attacker.attack / 30 + 1) * 4))
    damage = attacker.attack + extraAttack + opt.attack - defender.defend + defender.defend * opt.reduceDefendPer / 100
    if (damage < 0) {
        oper.damage = 0
        console.log(defender.name + '受到' + attacker.name + '的' + oper.damage + '伤害——————(' + attacker.name + '的hp:' + attacker.hp + '' + defender.name + '的hp:' + defender.hp + ')')
        return
    }
    oper.damage = Math.floor(damage * (damagePer + opt.damagePer - defender.reduceDamagePer - opt.reduceDamagePer) / 100)
    defender.hp = defender.hp - oper.damage
    if (attacker.vampirePer > 0 && attackType !== 3 && attacker.status !== 1) {
        hp = attacker.hp + oper.damage * attacker.vampirePer / 100
        oper.vampireHurt = hp < attacker.maxHp ? hp : attacker.maxHp
        attacker.hp = attacker.hp + oper.vampireHurt
    }
    console.log(defender.name + '受到' + attacker.name + '的' + oper.damage + '伤害——————(' + attacker.name + '的hp:' + attacker.hp + '' + defender.name + '的hp:' + defender.hp + ')')
    return
}

//计算胜利后的奖励
function calcReward(player1, player2, fightRecords) {
    results = []
    var getexp = player2.getexp
    var getmoney = player2.getmoney

    var items = calcDropItems(player2.dropItems)
    player1.exp += getexp
    player1.lvlupByExp()
    player1.money += getmoney
    var getItems = player1.bag.addItems(items)
    console.log(getItems)
    player1.saveBag()
    var result = {
        exp: getexp,
        money: getmoney,
        items: getItems
    }
    results.push(result)
    fightRecords.results = results
}

//根据概率计算物品掉落
function calcDropItems(items) {
    var item = []
    for (var i in items) {
        var flag
        switch (i) {
            case '1':
                flag = Math.floor(Math.random() * 100) < 30 ? true : false
                break
            case '2':
                flag = Math.floor(Math.random() * 100) < 15 ? true : false
                break
            case '3':
                flag = Math.floor(Math.random() * 100) < 5 ? true : false
                break
        }
        if (flag) {
            var l = Math.floor(Math.random() * items[i].length)
            item.push(items[i][l])
        }
    }
    return item
}

function recordFight(pid, data) {
    var dataStr = JSON.stringify(data)
    redisClient.rpush('lf:' + pid, dataStr)
    redisClient.ltrim('lf:' + pid, 0, 9)
}